﻿using ETA.Common;
using ETA.Entity;
using ETA.ExtendEntity;
using ETA.IRepository;
using NHibernate;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ETA.Repositories
{
    public class UserRepository : NhRepositoryBase<User, string>, IUserRepository
    {
        public List<UserView> GetFilterUser(out int rowCount, UserFilter filter)
        {
            rowCount = 0;
            var res = new List<UserView>();
            var session =  NHibernateHelper.GetSession();;
            using (var conn = session.Connection)
            {
                try
                {
                    var cmd = conn.CreateCommand() as SqlCommand;
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.CommandText = "GetUser";
                    cmd.Parameters.Add("@RolerId", SqlDbType.VarChar).Value = filter.RolerId;
                    cmd.Parameters.Add("@FlowStepId", SqlDbType.VarChar).Value = filter.FlowStepId;
                    
                    if (filter.ChangeStartTime != null)
                    {
                        cmd.Parameters.Add("@ChangeStartTime", SqlDbType.DateTime).Value = filter.ChangeStartTime.Value;
                    }

                    if (filter.ChangeEndTime != null)
                    {
                        cmd.Parameters.Add("@ChangeEndTime", SqlDbType.DateTime).Value = filter.ChangeEndTime.Value;
                    }

                    if (filter.IsActive != null)
                    {
                        cmd.Parameters.Add("@State", SqlDbType.Int).Value = filter.IsActive.Value ? 0 : 1;
                    }

                    cmd.Parameters.Add("@Page", SqlDbType.Int).Value = filter.Page;
                    cmd.Parameters.Add("@PageSize", SqlDbType.Int).Value = filter.PageSize;
                    SqlParameter rowCountP = cmd.Parameters.Add(new SqlParameter("@RowCount", SqlDbType.Int));
                    rowCountP.Direction = ParameterDirection.Output;

                    SqlDataAdapter sda = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    sda.Fill(ds);
                    rowCount = Convert.ToInt32(cmd.Parameters["@RowCount"].Value);

                    if (ds != null && ds.Tables.Count > 0)
                    {
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            res.Add(BindUserView(dr));  
                        }
                    }
                }
                catch (Exception ex)
                {                
                    throw ex;
                }
            }
            return res;
        }

        private UserView BindUserView(DataRow dr)
        {
            var model = new UserView();
            Object o = new Object();
            o = dr["UserId"];
            if(o!=DBNull.Value)
            {
                model.UserId = o.ToString();
            }

            o = dr["UserName"];
            if (o != DBNull.Value)
            {
                model.UserName = o.ToString();
            }

            o = dr["RolerName"];
            if (o != DBNull.Value)
            {
                model.RolerName = o.ToString();
            }

            o = dr["IsDelete"];
            if (o != DBNull.Value)
            {
                model.IsDelete = Convert.ToInt16(o);
            }

            o = dr["Note"];
            if (o != DBNull.Value)
            {
                model.Note = o.ToString();
            }

            return model;
        }


        public bool UpdateUserIsReferrer(string userId, int isReferrer)
        {
            ISession session = NHibernateHelper.GetSession();
            bool IsSuccess = false;

            ITransaction trans = session.BeginTransaction();
            try
            {
                string sql = " update [User] set isReferrer=:isReferrer where userId=:userId";
                var Query = session.CreateSQLQuery(sql).AddEntity(typeof(User))
                    .SetInt32("isReferrer", isReferrer)
                    .SetString("userId", userId);

                Query.ExecuteUpdate();
                session.Flush();
                trans.Commit();
                IsSuccess = true;
            }
            catch (Exception ex)
            {
                IsSuccess = false;
                Logger.LogInfo(ex.Message);
                trans.Rollback();
            }
            finally
            {
                if (session != null)
                {
                    session.Clear();
                }
            }
            return IsSuccess;
        }
    }
}
